package com.tavenli.services;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tavenli.entity.DeviceCmdEntity;
import com.tavenli.entity.F18Device;
import com.tavenli.entity.UserEntity;
import com.tavenli.model.PageData;
import com.tavenli.repository.DeviceCmdDao;
import com.tavenli.repository.F18DeviceDao;
import com.tavenli.utils.DateUtil;

@Service
public class IClockService {

	private static Logger logger = LoggerFactory
			.getLogger(UCenterService.class);

	@Autowired
	private F18DeviceDao f18DeviceDao;
	@Autowired
	private DeviceCmdDao deviceCmdDao;
	/**
	 * 设备注册
	 * 
	 * @return
	 */
	public boolean regF18Device(F18Device f18Device) {
		int deviceId = f18Device.getId();
		String sn = f18Device.getDeviceSn();
		if (deviceId > 0) {
			F18Device updatef18Device = this.f18DeviceDao.getF18DeviceById(deviceId);
			updatef18Device.setLastUpdate(DateUtil.getCurrentTime());
			if (StringUtils.isNotBlank(f18Device.getDeviceStamp())) {
				updatef18Device.setDeviceStamp(f18Device.getDeviceStamp());
			}
			if (StringUtils.isNotBlank(f18Device.getDeviceOpStamp())) {
				updatef18Device.setDeviceOpStamp(f18Device.getDeviceOpStamp());
			}
			try {
				this.f18DeviceDao.update(f18Device);
			} catch (Exception e) {
				logger.error(e.getMessage());
				return false;
			}
		} else {
			// 新增
			if (this.f18DeviceDao.existF18Device(sn)) {
				return false;
			}
			f18Device.setDeviceStatus(1);// 设为可用状态
			f18Device.setCreateTime(DateUtil.getCurrentTime());
			f18Device.setLastUpdate(DateUtil.getCurrentTime());
			try {
				this.f18DeviceDao.save(f18Device);
			} catch (Exception e) {
				logger.error(e.getMessage());
				return false;
			}
		}
		return true;
	}
	
	public PageData<F18Device> getF18Devices(int pageIndex, int pageSize,String deviceName){
		
		PageData<F18Device> pageData = new PageData<F18Device>(pageIndex, pageSize);
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("deviceName", deviceName);
		
		int totalCount = f18DeviceDao.queryDataCount(paramMap);
		List<F18Device> list = f18DeviceDao.queryPageData(pageData.getStartRow(), pageSize,paramMap);
		pageData.setTotalCount(totalCount);
		pageData.setPageData(list);
		
		return pageData;
		
	}
	/**
	 * 根据sn号判断设备是否已经注册
	 * 
	 * @param sn
	 * @return
	 */
	public boolean isRegF18Device(String sn) {
		return this.f18DeviceDao.existF18Device(sn);
	}
	/**
	 * 通过sn号获取设备信息
	 * @param sn
	 * @return
	 */
	public F18Device getF18DeviceBySn(String sn) {
		try {
			return this.f18DeviceDao.getSingleF18Device(sn);
		} catch (Exception e) {
			logger.error("查sn号 " + sn + " 数据出错");
		}
		return null;
	}
	/**
	 * 处理设备执行命令后的返回值
	 * @param sn
	 * @param retString
	 */
	public void dealDeviceCmd(String sn, String retString) {
		try {
			DeviceCmdEntity deviceCmdEntity=new DeviceCmdEntity();
			String ret[]=retString.split("\r\n");
			if (ret.length>0) {
				String firstLine=ret[0];
				Map<String, String> firstRetMap=getRetValueByLine(firstLine);
				int cmdId=Integer.parseInt(firstRetMap.get("ID"));
				deviceCmdEntity=deviceCmdDao.getDeviceCmdById(cmdId);
				if (null!=deviceCmdEntity) {
					int retVal=Integer.parseInt(firstRetMap.get("Return"));
					String typeString=firstRetMap.get("CMD");
					deviceCmdEntity.setCmdType(typeString);
					deviceCmdEntity.setRet(retVal);
					deviceCmdEntity.setLastUpdate(new Date());
					deviceCmdDao.update(deviceCmdEntity);
				}
			}
		} catch (Exception e) {
			logger.error("处理cmd命令 " + sn + " 数据出错");
		}
		
	}

	private Map<String, String> getRetValueByLine(String string) {
		Map<String, String> map=new HashMap<String, String>();
		String firstLine[]=string.split("&");
		for (int i = 0; i < firstLine.length; i++) {
			String tmp[]=firstLine[i].split("=");
			if (tmp.length>=2) {
				map.put(tmp[0], tmp[1]);
			}
		}
		return map;
	}

	public String sendCmdToDevice(String sn, String cmdContent) {
		try {
			DeviceCmdEntity deviceCmdEntity=new DeviceCmdEntity();
			deviceCmdEntity.setCmd(cmdContent);
			deviceCmdEntity.setCreateTime(new Date());
			deviceCmdEntity.setSn(sn);
			deviceCmdEntity=(DeviceCmdEntity) deviceCmdDao.saveAndRet(deviceCmdEntity);
			if(null!=deviceCmdEntity)
				return String.format("C:%d:%s", deviceCmdEntity.getId(),cmdContent);
		} catch (Exception e) {
			logger.error("生成cmd命令 " + sn + " 数据出错");
		}
		return null;
	}

	public F18Device getF18DeviceById(int id) {
		try {
			return f18DeviceDao.getF18DeviceById(id);
		} catch (Exception e) {
			logger.error("获取设备id号为： " + id + " 数据出错");
		}
		return null;
	}
	@Transactional(readOnly = false)
	public int delDevice(int id) {
		return f18DeviceDao.delDevice(id);
	}
	@Transactional(readOnly = false)
	public int delDevices(Integer[] deviceIds) {
		return f18DeviceDao.delDevices(deviceIds);
	}

}
